package com.cookie.realm;

import com.cookie.api.model.DTO.UserDTO;
import com.cookie.api.model.PO.User;
import com.cookie.api.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户名密码Realm
 *
 * @author DELL
 */
@Component
public class PasswordRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principalCollection 权限
     * @return 授权过后的认证信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     *
     * @param token 令牌
     * @return 认证信息
     * @throws AuthenticationException 认证错误
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        User user = new User().setName(username).setPassword(password);
        UserDTO login;
        try {
            login = userService.login(new UserDTO(user));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage());
        }
        if (User.Status.DISABLE.getValue().equals(login.getUser().getStatus())) {
            throw new AuthenticationException("user.login.disable");
        }
        return new SimpleAuthenticationInfo(login.getUser(), user.getPassword(), getName());
    }
}
